package com.kedacom.demo.redis.jedis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * RedisUtils
 * @author luocanfeng
 * @date 2015年8月6日
 */
public class RedisUtils {

	private static final String redis_ip = "172.16.80.113";
	private static final int redis_port = 6379;
	private static final String redis_password = null;

	private static final int max_total = 1; // 最大连接数
	private static final int max_idle = 1; // 最大空闲连接数
	private static final int max_wait_millis = 1000; // 等待可用连接的最大时间，单位毫秒
	private static final boolean test_on_borrow = false; // 在borrow一个连接时，是否提前进行validate操作；如果为true，则得到的连接均是可用的
	private static final int opt_timeout = 1000;

	private static JedisPool jedisPool = null;

	static {
		try {
			JedisPoolConfig config = new JedisPoolConfig();
			config.setMaxTotal(max_total);
			config.setMaxIdle(max_idle);
			config.setMaxWaitMillis(max_wait_millis);
			config.setTestOnBorrow(test_on_borrow);
			jedisPool = redis_password == null ? new JedisPool(config, redis_ip, redis_port, opt_timeout)
					: new JedisPool(config, redis_ip, redis_port, opt_timeout, redis_password);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Jedis getJedis() {
		try {
			return jedisPool == null ? null : jedisPool.getResource();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void returnJedis(final Jedis jedis) {
		if (jedisPool != null && jedis != null) {
			jedisPool.returnResourceObject(jedis);
		}
	}

	public static JedisPool getJedisPool() {
		return jedisPool;
	}

}
